import { resolve } from 'path';
import { defineConfig, loadEnv, ConfigEnv } from 'vite';
import { getPluginsList } from "./build/plugins";
import { include, exclude } from "./build/optimize";
import { external } from "./build/cdn";
const pathResolve = (dir: string): any => {
	return resolve(__dirname, '.', dir);
};

const alias: Record<string, string> = {
	'@': pathResolve('./src/'),
};

const viteConfig = defineConfig(({ command, mode }: ConfigEnv) => {
	const env = loadEnv(mode, process.cwd());
	return {
		plugins: getPluginsList(command, JSON.parse(env.VITE_OPEN_CDN), "gzip"),
		root: process.cwd(),
		resolve: { alias },
		base: env.VITE_PUBLIC_PATH,
		optimizeDeps: {
			include,
			exclude
		},
		server: {
			open: JSON.parse(env.VITE_OPEN),
			host: '127.0.0.1',
			port: env.VITE_PORT as unknown as number,
			hmr: true,
			proxy: {
				'/dyedu': {
					target: 'http://localhost:9091',
					ws: true,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/bifang-api/, ''),
				},
			},
		},
		build: {
			minify: 'terser',
			outDir: 'dist',
			sourcemap: false,
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				input: {
					index: pathResolve("index.html")
				},
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
					compact: true,
					manualChunks(id :any) {
						if (id.includes('tsparticles')) {
							return 'npm-tsparticles';
						} else if (id.includes('node_modules')) {
							return 'npm-' + id.toString().split('node_modules/')[1].split('/')[0].toString();
						} else if (id.includes('src')) {
							return 'manifest';
						}
					},
				},
				...(JSON.parse(env.VITE_OPEN_CDN) ? {external: external} : {}),
			},
			terserOptions: {
				compress: {
					drop_console: true,
					drop_debugger: true,
					pure_funcs: ['console.log'],
				},
				ie8: true,
				output: {
					comments: true,
				},
				keep_classnames:true,
			},
			assetsDir: './static',
			minify: 'terser',
			cssCodeSplit: true, // 如果设置为false，整个项目中的所有 CSS 将被提取到一个 CSS 文件中
			brotliSize: false,
		},
		css: {
			preprocessorOptions: {
				css: { charset: false },
				less: {
					javascriptEnabled: true,
				},
			},
		},
		define: {
			__VUE_I18N_LEGACY_API__: JSON.stringify(false),
			__VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
			__INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
			__VERSION__: JSON.stringify(process.env.npm_package_version),
			__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
			__NEXT_NAME__: JSON.stringify(process.env.npm_package_name),
		},
	};
});

export default viteConfig;
